// pages/plateNumList/plateNumList.js
var util = require('../../utils/request.js');
var globalData = getApp().globalData;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    //订单信息
    orderInfo: {},
    noOrder: true,
    cardId: '',
    card: [],
    current: '0',
    animation: '',
    startX: 0, //开始坐标
    startY: 0
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.getCard();
  },
  selectCoupon: function() {
    wx.navigateTo({
      url: '../coupon/coupon',
    })
  },
  changeSelect: function(e) {
    var that = this;
    var current = e.detail.current;
    var card = this.data.card;
    this.setData({
      current
    })

    if (card[current] && card[current].ID != null) {
      this.setData({
        cardId: card[current].licensePlateId
      })
      this.getOrder();
    } else {
      this.setData({
        noOrder: true
      })
    }
    console.log(this.data.current);
  },
  //去支付
  goPay: function() {
    var that = this
    util.req('/order/finish', {
      sn: this.data.orderInfo.sn,
      memberId: globalData.memberId,
      parkType: this.data.orderInfo.parkType
    }, function(success) {
      if (success.resultCode == 200) {
        wx.redirectTo({
          url: '../payOrder/payOrder?sn=' + that.data.orderInfo.sn,
        })
      } else if (res.resultCode == 400) {
        wx.showToast({
          title: res.resultMsg,
          icon: 'none'
        })
      } else {
        wx.showToast({
          title: '结束订单错误！',
          icon: 'none'
        })
      }
    })

  },
  // 点击车牌
  addCard: function(e) {
    var that = this;
    if (!e.currentTarget.id) {
      // 添加
      wx.navigateTo({
        url: '../addCard/addCard',
      })
    } else {
      // 修改、删除
      wx.showActionSheet({
        itemList: ['修改', '删除'],
        success: function(res) {
          console.log(res)
          var cardNumber = that.data.card[that.data.current];
          console.log(cardNumber);
          if (res.tapIndex == 0) {
            // 修改
            wx.navigateTo({
              url: '../addCard/addCard?number=' + cardNumber.number + '&licensePlateId=' + cardNumber.licensePlateId + '&type=' + cardNumber.type,
            })
          } else if (res.tapIndex == 1) {
            // 删除
            console.log(cardNumber);
            util.req('/licensePlate/delLicensePlate', {
              'licensePlateId': cardNumber.licensePlateId,
              'memberId': globalData.memberId
            }, function(data) {
              console.log(data);
              if (data.resultCode == 200) {
                wx.showToast({
                  title: data.resultMsg,
                })
                that.getCard();
              } else {
                wx.showToast({
                  title: data.resultMsg,
                  icon: 'none'
                })
              }
            })
          }
        },
        fail: function(res) {
          console.log(res.errMsg)
        }
      })
    }
  },
  // 获取车牌列表
  getCard() {
    var that = this;
    util.req('/licensePlate/myLicensePlate', {
      'memberId': globalData.memberId
    }, function(res) {
      console.log(res);
      if (res.resultContent.length <= 0) {
        wx.redirectTo({
          url: '../addCard/addCard',
        })
      } else {
        var card = [];
        res.resultContent.forEach(function(item) {
          item.name = item.number.slice(0, 2);
          item.ID = item.number.slice(2);
          card.push(item);
          item.isTouchMove = false;
        })
        // if (card.length <= 9) {
        //   card.push({
        //     type: 'ordinary',
        //     hasCard: false
        //   });
        // }
        that.setData({
          card: card
        })
        if (card.length != 0) {
          that.setData({
            cardId: card[0].licensePlateId
          })
          that.getOrder();
        }
      }
    })
  },
  //刷新缴费信息
  refreshOrder: function() {
    var that = this;
    this.setData({
      animation: true,
    })
    setTimeout(function() {
      that.setData({
        animation: '',
      })
    }, 1000)
    this.getOrder();
  },
  //获取实时缴费信息
  getOrder: function() {
    var that = this;
    var card = this.data.card;
    var current = this.data.current;
    var name = card[current] && card[current].number;
    // console.log(name);
    util.req('/order/refreshParkingOrder', {
      number: name
    }, function(success) {
      console.log(success)
      if (success.resultCode == 200) {
        var orderInfo = {
          finishDate: util.formatTime(success.resultContent.finishDate),
          orderDuration: util.formatSeconds(success.resultContent.orderDuration),
          business: success.resultContent.business,
          useDate: util.formatTime(success.resultContent.useDate),
          card: success.resultContent.number,
          amount: Math.floor(success.resultContent.amount * 100) / 100,
          parkType: success.resultContent.parkType,
          sn: success.resultContent.sn
        }
        that.setData({
          orderInfo: orderInfo,
          noOrder: false
        })
      } else {
        that.setData({
          noOrder: true
        })
      }
    })
  },
  //手指触摸动作开始 记录起点X坐标
  touchstart: function(e) {
    //开始触摸时 重置所有删除
    this.data.card.forEach(function(v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false;
    })
    this.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      card: this.data.card
    })
  },
  //滑动事件处理
  touchmove: function(e) {
    var that = this,
      index = e.currentTarget.dataset.index, //当前索引
      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      //获取滑动角度
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      });
    that.data.card.forEach(function(v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (i == index) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })
    //更新数据
    that.setData({
      card: that.data.card
    })
  },
  /**
   * 计算滑动角度
   * @param {Object} start 起点坐标
   * @param {Object} end 终点坐标
   */
  angle: function(start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },
  /**
   * 删除车牌
   */
  _del: function(e) {
    var that = this;
    var url = '/licensePlate/delLicensePlate';
    var {
      currentIndex
    } = e.currentTarget.dataset;
    var currentCard = this.data.card[currentIndex];

    var paramsData = {
      'licensePlateId': currentCard.licensePlateId,
      'memberId': globalData.memberId
    }
    util.req(url, paramsData, function(data) {
      if (data.resultCode == 200) {
        wx.showToast({
          title: data.resultMsg,
        })
        that.getCard();
      } else {
        wx.showToast({
          title: data.resultMsg,
          icon: 'none'
        })
      }
    })

  },
  /**
   * 设置默认车牌
   */
  _setDefault(e) {
    var that = this;
    var {
      currentPlate
    } = e.currentTarget.dataset;
    var url = '/licensePlate/updateLicensePlateTacitly';
    var parmasData = {
      'licensePlateId': currentPlate,
      'memberId': globalData.memberId
    }
    util.req(url,parmasData,function(res){
        that.getCard();
      })
  },
  /**
   *编辑车牌
   */
  _edit(e) {
    var {
      currentIndex
    } = e.currentTarget.dataset;

    var currentCard = this.data.card[currentIndex];

    wx.navigateTo({
      url: '../addCard/addCard?number=' + currentCard.number + '&licensePlateId=' + currentCard.licensePlateId + '&type=' + currentCard.type
    })

  }
})